package com.example.ccj.b.c.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.ccj.R;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.text.TextInputType;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * TextInputLayout输入模块，表单模块 上下显示
 * 上面可以提示文本验证
 * 2021年9月29日
 */
public class InputCheckWithUpAndDown extends RelativeLayout {

//    private final TextView fieldName;
    private  ImageView mIvLeftImage;
    private  ImageView mIvRightImage;
    private  TextInputLayout mTiLayout;
    private  TextInputEditText mTiEditText;
    private  LinearLayout mLlContent;
    private  LinearLayout mLlCon;
    private boolean checkIsNull  = false, checkLength = false,isTime = false;
    private int textLength;
    private TextModify textModify;
    private String sqlFieldName;//sq字段名

    public InputCheckWithUpAndDown(Context context) {
        super(context);
        init();
    }


    public InputCheckWithUpAndDown(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.InputCheckWithUpAndDown);
        if (typedArray != null) {
            String string = typedArray.getString(R.styleable.InputCheckWithUpAndDown_form_in_put_field_name);
            String hint = typedArray.getString(R.styleable.InputCheckWithUpAndDown_form_in_put_hint);
            boolean required = typedArray.getBoolean(R.styleable.InputCheckWithUpAndDown_form_in_put_required,false);
            if (string != null) {
                mTiLayout.setHint(hint);
//                fieldName.setText(string);
            }
            if (required) setCheckIsNull("不可为空");

            typedArray.recycle();
        }
    }

    private void init(){
        LayoutInflater.from(getContext()).inflate(R.layout.custom_form_text_input_layout, this);
        mIvLeftImage = findViewById(R.id.my_text_input_layout_left_image);
        mIvRightImage = findViewById(R.id.my_text_input_layout_right_image);
        mTiLayout = findViewById(R.id.my_text_input_layout_text_input_layout);
        mTiEditText = findViewById(R.id.my_text_input_layout_text_input_edittext);
        mLlContent = findViewById(R.id.my_text_input_layout_content);
        mLlCon = findViewById(R.id.my_text_input_layout_left_linder);

        mTiEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
            @Override
            public void afterTextChanged(Editable editable) {
                mTiLayout.setErrorEnabled(false);
//                LogUtil.d("检查字段");
                if (checkIsNull) {
//                    LogUtil.d("不可为空");
                    if(TextUtils.isEmpty(editable.toString())){
                        showError(textIsNullTip);
                        isNull = true;
                    }
                }
                if (checkLength) {
//                    LogUtil.d("最大长度："+textLenght);
                    if (!TextUtils.isEmpty(editable.toString())) {
                        if(editable.toString().length() > textLength){
                            showError("数据过长，最长"+ textLength);
                            lenght = true;
                        }
                    }
                }
                if (isTime) {
//                    LogUtil.d("是否日期");
                    if(TextUtils.isEmpty(editable.toString()) || !checkTimeFormat(editable.toString())){
                        showError("请输入日期格式文本！");
                        isTime1 = true;
                    }
                }
                if (textModify != null) textModify.onTextModify(sqlFieldName,editable.toString());
            }
        });
        mTiLayout.setErrorEnabled(false);
    }

    boolean isNull = false,lenght = false,isTime1 = false;

    public boolean getTextIsError(){
        return mTiLayout.isErrorEnabled();
    }
    //文本修改事件
    public InputCheckWithUpAndDown setTextModifyListener(TextModify textModify){
        this.textModify = textModify;
        return this;
    }

    //设置字段名称
    public InputCheckWithUpAndDown setFieldName(String sqlFieldName){
        this.sqlFieldName = sqlFieldName;
        return this;
    }

    public String getFieldName(){
        return sqlFieldName;
    }

    //设置是否显示错误提示
    public void setErrorEnabled(boolean isShow){
        mTiLayout.setErrorEnabled(isShow);
    }


    /**
     * 设置文本框只能输入数字
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setOnlyNumber(Boolean onlyNumber){
        if (onlyNumber) TextInputType.setEditTextInPutTypeToInt(mTiEditText);
        else mTiEditText.setInputType(InputType.TYPE_NULL);
        return this;
    }

    private boolean isShowPassWord = false;

    //显示为密码
    public InputCheckWithUpAndDown setInputTypeIsPassWord(){
        mTiEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        return this;
    }

    /**
     * 设置密码验证
     * @return
     */
    public InputCheckWithUpAndDown setRightIconIsPassWord(){
        showRightImage(R.mipmap.pass_word_hide, new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowPassWord) {
                    isShowPassWord = false;
                    mIvRightImage.setImageResource(R.mipmap.pass_word_hide);
                    setInputTypeIsPassWord();
                } else {
                    isShowPassWord = true;
                    mIvRightImage.setImageResource(R.mipmap.pass_word_show);
                    setInputTypeNoPassWord();
                }
            }
        });
        return this;
    }

    //显示为明文
    public InputCheckWithUpAndDown setInputTypeNoPassWord(){
        mTiEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        return this;
    }
    /**
     * 设置文本框只能输入小数
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setOnlyDouble(Boolean onlyDouble){
        if (onlyDouble) {
            mTiEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            TextInputType.setEditTextInPutTypeToDouble(mTiEditText);
        } else {
            mTiEditText.setInputType(InputType.TYPE_NULL);
        }
        return this;
    }

    /**
     * 设置中间的点击事件
     * @param clickListener 图片点击事件
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setTextInputLayoutListener(OnClickListener clickListener){
        mTiEditText.setEnabled(false);
        mTiLayout.setEnabled(false);
        if (clickListener != null)  mLlContent.setOnClickListener(clickListener);
        return this;
    }

    public InputCheckWithUpAndDown setTextEnabled(boolean is){
        mTiEditText.setKeyListener(null);
        mTiLayout.setEnabled(is);
        if (is) {
//            mLlCon.setBackgroundResource(R.drawable.custom_style_edit_green_r10);
        }else {
//            mLlCon.setBackgroundResource(R.drawable.custom_style_edit_grey_r10);
        }
        return this;
    }

    /**
     * 显示左侧图片并设置点击事件
     * @param imageId 图片ID
     * @param clickListener 图片点击事件
     * @return 返回本类
     */
    public InputCheckWithUpAndDown showLeftImage(int imageId, OnClickListener clickListener){
        mIvLeftImage.setVisibility(VISIBLE);
        mIvLeftImage.setImageResource(imageId);
        if (clickListener != null)  mIvLeftImage.setOnClickListener(clickListener);
        return this;
    }

    /**
     * 显示右侧图片并设置点击事件
     * @param imageId 图片ID
     * @param clickListener 图片点击事件
     * @return 返回本类
     */
    public InputCheckWithUpAndDown showRightImage(int imageId, OnClickListener clickListener){
        mIvRightImage.setVisibility(VISIBLE);
        mIvRightImage.setImageResource(imageId);
        if (clickListener != null)  mIvRightImage.setOnClickListener(clickListener);
        return this;
    }

    String textIsNullTip = "";
    /**
     * 设置验证是否为空
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setCheckIsNull(String textIsNullTip){
        this.textIsNullTip = textIsNullTip;
        checkIsNull = true;
        if (StringUtils.isEmpty(getEditText())) showError(textIsNullTip);
        return this;
    }

    boolean isMast = false;
    /**
     * 设置验证是否为空
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setMast(){
        this.textIsNullTip = textIsNullTip;
        checkIsNull = true;
        return this;
    }


    /**
     * 返回输入框
     * @return 返回本类
     */
    public TextInputEditText getTextInputEditText(){
        return mTiEditText;
    }

    /**
     * 打开计数
     * @return 返回本类
     */
    public InputCheckWithUpAndDown openCounter(){
        mTiLayout.setCounterEnabled(true);
        return this;
    }

    /**
     * 设置验证文本长度
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setCheckLength(int len){
        mTiEditText.setMaxLines(len);
        checkLength = true;
        textLength = len;
        return this;
    }

    /**
     * 设置文本框提示文字
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setTextHint(String hint){
        mTiLayout.setHint(hint);
        return this;
    }


    /**
     * 返回提示文字
     * @return 返回本类
     */
    public String getTextHint(){
        if (mTiLayout.getHint() != null) {
            return mTiLayout.getHint().toString();
        }
        return "";
    }

    /**
     * 检查是否日期
     * @param isTime
     * @return
     */
    public InputCheckWithUpAndDown checkIsTime(boolean isTime){
        this.isTime = true;
        return this;
    }

    /**
     * 获取文本框文字
     * @return 返回本类
     */
    public String getEditText(){
        if (mTiEditText.getText() != null) {
            return mTiEditText.getText().toString();
        }
        return "";
    }

    /**
     * 设置文本框文本
     * @param text 文本内容
     * @return 返回本类
     */
    public InputCheckWithUpAndDown setText(@NonNull String text){
        mTiEditText.post(new Runnable() {
            @Override
            public void run() {
                mTiEditText.setText(text);
                mTiLayout.setErrorEnabled(false);

                if (checkIsNull) {
                    if(TextUtils.isEmpty(text)){
                        showError("字段不能为空");
                    }
                } else if (checkLength) {
                    if (!TextUtils.isEmpty(text)) {
                        if(text.length() > textLength){
                            showError("数据过长，最长"+ textLength);
                        }
                    }
                } else if (isTime) {
                    if(TextUtils.isEmpty(text) || !checkTimeFormat(text)){
                        showError("请输入日期格式文本！");
                    }
                }
            }
        });

        return this;
    }

    public boolean isError(){
        return mTiLayout.isErrorEnabled();
    }

    /**
     * 显示错误提示，并获取焦点
     * @param error 3
     */
    public void showError(String error){
        mTiLayout.setError(error);
        if (mTiLayout.getEditText() != null) {
            mTiLayout.getEditText().setFocusable(true);
        }
    }

    public interface TextModify{
        void onTextModify(String sqlFieldName,String text);
    }

    /**
     * 通过正则表达式检查是否符合时间格式
     */

    @SuppressWarnings("unused")
    private boolean checkTimeFormat(String validateDate) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = "2008-09-06";
        Date d = null;
        try{
            d = format.parse(str);
            return true;
        }catch(Exception ex){
            // 字符串不是日期
            return false;
        }
    }
}
